let _Vue = null
export default class MyRouter {
    constructor(options) {
        this.options = options
        this.routerMap = {}
        this.data = _Vue.observable({
            current: "/home"
        })
    }

    initRouterMap() {
        this.options.routes.forEach(route => {
            this.routerMap[route.path] = route.component
        })
    }

    initComponents() {
        _Vue.component("router-link", {
            props: {
                to: {
                    type: String
                }
            },
            render(h) {
                return h("a", {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, this.$slots.default)
            },
            methods: {
                clickHandler(e) {
                    e.preventDefault()
                    window.location.hash = this.to
                }
            }
        })

        _Vue.component("router-view", {
            render(h) {
                const component = this.$router.routerMap[this.$router.data.current]
                return h(component)
            }
        })
    }

    initEvents() {
        window.addEventListener("hashchange", () => {
            this.data.current = window.location.hash.slice(1)
        })
    }

    init() {
        this.initRouterMap()
        this.initComponents()
        this.initEvents()
    }

    static install(Vue) {
        _Vue = Vue
        if (MyRouter.install.installed) return;
        MyRouter.install.installed = true

        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }
}